import 'package:family_expense/features/account_user/models/account_group.dart';
import 'package:my_flutter_core/my_flutter_core.dart';

/// The service communicates with backend for [AccountGroup] usage.
class AccountGroupService {
  final String _url = '/account-group';
  final String _accountGroupSharingKey = 'accountGroup';
  final HttpRequestService _httpRequestService = HttpRequestService();

  /// Gets the loaded data.
  AccountGroup? get currentAccountGroup {
    return DataSharing.get<AccountGroup>(_accountGroupSharingKey);
  }

  set currentAccountGroup(AccountGroup? accountGroup) {
    DataSharing.set<AccountGroup>(_accountGroupSharingKey, accountGroup);
  }

  /// Loads the data when it is not ready yet.
  ///
  /// [AccountGroup] is the data provided by other service. If this is not null then we don't have to load it again from server.
  Future<void> init({AccountGroup? loadedAccountGroup}) async {
    // Loads the data from server if [loadedAccountGroup] is null.
    var accountGroup = loadedAccountGroup ?? await queryAccountGroupInfo();

    // Caches the data.
    DataSharing.set<AccountGroup>(_accountGroupSharingKey, accountGroup);
  }

  // Clears cache data.
  void clearCache() {
    DataSharing.remove(key: _accountGroupSharingKey);
  }

  /// Retrieves the [AccountGroup] from backend service.
  Future<AccountGroup> queryAccountGroupInfo() async {
    // Gets the response of the http get request.
    final response =
        await _httpRequestService.get('$_url/query-account-group-info');

    // Parses the data from [Map<String, dynamic>] to [AccountGroup].
    final accountGroup = AccountGroup.fromJson(response.payload);

    return accountGroup;
  }

  /// Queries basic statistics including totalIncomeExpenseCount and totalIncomeExpenseDays.
  Future<Map<String, dynamic>> queryBasicStatistics() async {
    // Gets the response of the http get request.
    final response =
        await _httpRequestService.get('$_url/query-basic-statistics');

    return response.payload as Map<String, dynamic>;
  }

  /// Updates the [AccountGroup] info.
  Future<void> update(AccountGroup accountGroup) async {
    await _httpRequestService.post('$_url/update', body: accountGroup.toJson());

    // Updates the cache data.
    DataSharing.set<AccountGroup>(
        _accountGroupSharingKey, accountGroup.clone());
  }
}
